package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.ApArticleMapper;
import com.usian.article.mapper.CollectionMapper;
import com.usian.article.service.CollectionBehaviorService;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CollectionBehaviorServiceImpl extends BaseServiceImpl<CollectionMapper, ApCollection> implements CollectionBehaviorService {
    @Autowired
    private BehaviorFeign feign;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult like(CollectionBehaviorDto dto) {
        if (dto == null || dto.getArticleId() == null || dto.getOperation() == null) return paramError;
        if (dto.getOperation() != 0 && dto.getOperation() != 1) return paramError;
        if (dto.getType() == null) dto.setType((short) 0);
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return needLogin;
        ApBehaviorEntry byUserId = feign.findByUserId(userId);
        ApArticle apArticle = apArticleMapper.selectById(dto.getArticleId());
        if (apArticle == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "收藏的新闻不存在");
        LambdaQueryWrapper<ApCollection> wrapper = Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getArticleId()).eq(ApCollection::getEntryId, byUserId.getId());
        ApCollection collection = getOne(wrapper);
        if (collection == null) {
            if (dto.getOperation() == 0) {
                ApCollection apCollection = new ApCollection();
                apCollection.setArticleId(dto.getArticleId());
                apCollection.setCollectionTime(new Date());
                apCollection.setPublishedTime(apArticle.getPublishTime());
                apCollection.setType(dto.getType());
                apCollection.setEntryId(byUserId.getId());
                save(apCollection);
            } else return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "没有该收藏记录");
        } else {
            if (dto.getOperation() == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "不能重复收藏");
            } else {
                baseMapper.delete(wrapper);
            }
        }
        return okResult;
    }
}
